package com.example.test.content;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.test.R;

public class MyContentProviderActivity extends Activity {

	private Button btn_insertRecord;
	private Button btn_queryRecord;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contentproider_main);

		btn_insertRecord = (Button) findViewById(R.id.btn_insertRecord);
		btn_queryRecord = (Button) findViewById(R.id.btn_queryRecord);

		btn_insertRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				for (int i = 0; i < 5; i++) {
					insertRecord("cping" + i);
				}
			}
		});
		btn_queryRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				displayRecords();
			}
		});

	}

	private void insertRecord(String userName) {
		ContentValues values = new ContentValues();
		values.put(MyUsers.User.USER_NAME, userName);
		getContentResolver().insert(MyUsers.User.CONTENT_URI, values);
	}

	private void displayRecords() {
		String columns[] = new String[] { MyUsers.User._ID,
				MyUsers.User.USER_NAME };
		Uri myUri = MyUsers.User.CONTENT_URI;
		Cursor cur = getContentResolver().query(myUri, columns, null, null,
				null);
		if (cur.moveToFirst()) {
			String id = null;
			String userName = null;
			do {
				id = cur.getString(cur.getColumnIndex(MyUsers.User._ID));
				userName = cur.getString(cur
						.getColumnIndex(MyUsers.User.USER_NAME));
				Toast.makeText(this, id + " " + userName, Toast.LENGTH_LONG)
						.show();
			} while (cur.moveToNext());
		}
	}
}
